import ImgCropperModalType from '@/platform/types/img-cropper-modal-type';
import { Modal, Button, notification } from 'antd';
import React, { useRef, useState } from 'react';
import PropTypes from 'prop-types';
import defaultSquareImg from '@/assets/platform/img/img-cropper/default-square-img.png';
import defaultCircularImg from '@/assets/platform/img/img-cropper/default-circular-img.png';
import Cropper from "react-cropper";
import CommonUtil from '@/platform/commons/utils/common-util';
import DynamicIcon from '../dynamic-icon/DynamicIcon';
import CustomImg from '../custom-img/CustomImg';
import classes from './ImgCropperModal.module.less';

const previewCls = ('app-img-cropper-modal-preview-' + CommonUtil.randomLetter(8));

const ImgCropperModal:React.FC<ImgCropperModalType> = (props:ImgCropperModalType) => {
    const circularImg = defaultCircularImg;
    const squareImg = defaultSquareImg;
    const [imgSrc, setImgSrc] = useState('');
    const [cropper, setCropper] = useState<Cropper>();
    
    const uploadInputRef = useRef<any>();

    const selectFile = (e: any): void => {
        const file: any = e.target.files[0];
        const fileSize = file.size;
        if (fileSize > (props.maxSize || 0)) {
            notification.warning({
                message: '提示',
                description: `请${props.browseBtnText}小于${props.maxSize}的图片!`
            });
            uploadInputRef.current.value = '';
            return;
        }
  
        const reader: any = new FileReader();
        reader.onload = (): void => {
            setImgSrc(reader.result);
            uploadInputRef.current.value = '';
        };
        reader.readAsDataURL(file);
    };


    const upload = () => {
        if (!(cropper) || cropper?.getCroppedCanvas() === null) {
            notification.warning({
                message: '提示',
                description: `请${props.browseBtnText}图片!`
            });
            return;
        }
        
        const imgData = cropper?.getCroppedCanvas().toDataURL();
  
        if (!!imgData && imgData.length) {
            props.onUpload && props.onUpload(imgData);
        } else {
            notification.warning({
                message: '提示',
                description: `请${props.browseBtnText}图片!`
            });
        }
    };

    /**
     * 取消
     */
    const handleCancel = () => {
        props.onCancel && props.onCancel();
    };

    const footer = () => (
        <div className={classes["app-img-cropper-btns"]}>
            <div className={[classes['app-img-cropper-upload-btn'], props.uploadBtnCls].join(' ')}>
                <Button icon={<DynamicIcon iconName={props.browseBtnIcon} />}>
                    {props.browseBtnText}
                </Button>
                <input
                    ref={uploadInputRef}
                    type="file"
                    accept={props.accept}
                    onChange={selectFile}
                />
            </div>

            <Button type="primary" icon={<DynamicIcon iconName={props.uploadBtnIcon} />} onClick={upload}>
                { props.uploadBtnText }
            </Button>
        </div>
    )
    
    return (
        <Modal
            destroyOnClose 
            forceRender
            width={660}
            visible
            maskClosable={props.maskClosable}
            keyboard={props.keyboard}
            zIndex={props.zIndex}
            title={props.title}
            onCancel={handleCancel}
            footer={footer()}
        >
            <div className={classes["app-img-cropper-modal-container"]}>
                <div className={[classes['app-img-cropper-cut-container'], props.imgCropperCutCls].join(' ')}>
                    <Cropper
                        src={imgSrc}
                        style={{ height: 350, width: '100%', background: '#f8f8f8' }}
                        aspectRatio={1 / 1}
                        viewMode={1}
                        minCropBoxWidth={100}
                        minCropBoxHeight={100}
                        movable={false}
                        zoomable={false}
                        guides={false}
                        preview={'.' + previewCls}
                        onInitialized={(instance) => {
                            setCropper(instance);
                        }}
                    />
                </div>
                <div className={[classes['app-img-preview-container'], props.imgPreviewCls].join(' ')}>
                    <div className={classes["app-img-preview-title"]}>{props.previewTitle }</div>
                    <div className={classes["app-original-img"]}>
                        <CustomImg imgSrc={props.originalImgSrc} errSrc={props.previewSquare ? squareImg : circularImg} imgClassName={[props.previewSquare ? classes['app-img-preview-square'] : classes['app-img-preview-round']]} />
                        <div className={classes["app-preview-img-label"]}>{ props.originalImgLabel }</div>
                    </div>
                    <div className={classes["app-preview-lg-img"]}>
                        <div
                            className={[
                                classes['app-img-cropper-preview'],
                                previewCls,
                                props.previewSquare ? classes['app-img-preview-square'] : classes['app-img-preview-round']
                            ].join(' ')}
                        />
                        <div className={classes["app-preview-img-label"]}>64*64</div>
                    </div>
                    <div className={classes["app-preview-sm-img"]}>
                        <div
                            className={[
                                classes['app-img-cropper-preview'],
                                previewCls,
                                props.previewSquare ? classes['app-img-preview-square'] : classes['app-img-preview-round']
                            ].join(' ')}
                        />
                        <div className={classes["app-preview-img-label"]}>32*32</div>
                    </div>
                </div>
            </div>

            <div className={classes["app-img-cropper-alert"]}>
                注：请上传小于
                { props.maxSize && props.maxSize / 1024 / 1024 }
                M的JPG/JPEG、PNG、GIF图片。
            </div>
        </Modal>
    )
};

ImgCropperModal.defaultProps = {
    title: '图片裁剪',
    maskClosable: false,
    keyboard: false,
    zIndex: 1001,
    imgCropperCutCls: '',
    imgPreviewCls: '',
    uploadBtnCls: '',
    previewTitle: '图片预览',
    originalImgLabel: '原图片',
    originalImgSrc: '',
    maxSize: 8388608,
    previewSquare: false,
    browseBtnText: '选择',
    uploadBtnText: '上传',
    uploadBtnIcon: 'CloudUploadOutlined',
    browseBtnIcon: 'SearchOutlined',
    onCancel: () => {},
    onUpload: () => {}
};
ImgCropperModal.propTypes = {
    title: PropTypes.string,
    maskClosable: PropTypes.bool,
    keyboard: PropTypes.bool,
    zIndex: PropTypes.number,
    imgCropperCutCls: PropTypes.string,
    imgPreviewCls: PropTypes.string,
    uploadBtnCls: PropTypes.string,
    previewTitle: PropTypes.string,
    originalImgLabel: PropTypes.string,
    originalImgSrc: PropTypes.string,
    maxSize: PropTypes.number,
    previewSquare: PropTypes.bool,
    browseBtnText: PropTypes.string,
    uploadBtnText: PropTypes.string,
    uploadBtnIcon: PropTypes.string,
    browseBtnIcon: PropTypes.string,
    onCancel: PropTypes.func,
    onUpload: PropTypes.func
};

export default ImgCropperModal;
